package com.example;

import obix.Obj;
import obix.Uri;
import obix.net.ObixSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ObixClientWithRW {
    private ObixSession session;
    private String baseUrl;
    private String userName;
    private String password;
    private Logger log = LoggerFactory.getLogger("Demo");

    public ObixClientWithRW(String baseUrl, String userName, String password) {
        this.baseUrl = baseUrl;
        this.userName = userName;
        this.password = password;
        init();
    }

    private void init() {
		Uri uri = new Uri(baseUrl);
		log.info("init-obix with {},{},{}"+baseUrl+":"+userName+":"+password);
		session = new ObixSession(uri, userName, password);
		try {
			session.open();
			log.info("init-obix with {},{},{} session opened."+":"+baseUrl+":"+userName+""+password);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("session open failed", e);
		}
    }

    public Obj read(String url) {
        try {
            // 根据我们传进去的url中读出一个obj,然后返回<obj>

            Obj obj = session.read(new Uri(url));
            return obj;
        } catch (Exception e) {
            try {
                Thread.sleep(1000);
                log.warn("read url" + url + " failed, sleep 1s to have a rest");
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            log.error("error reading obix: ", e);
            return null;
        }
    }
}